import React, {useEffect, useState} from 'react';
import MarkdownIt from "markdown-it";
import MdEditor from 'react-markdown-editor-lite';
import 'react-markdown-editor-lite/lib/index.css';
import {Button, Form, Input, message} from "antd";
import {useLocation, useParams} from "react-router-dom";

const mdParser = new MarkdownIt(/* Markdown-it options */);

const MarkdownEditor = () => {
    const location = useLocation()
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm();
    const [content, setContent] = useState('');

    useEffect(() => {
        if(location.state?.content){
            setContent(location.state.content)
        }
    }, []);
    const onSubmit = () => {
        if(!content){
            messageApi.open({
                type: 'error',
                content: '请输入内容',
            });
            return
        }
        form.validateFields().then(values => {
            if(values){
                addNote({
                    ...values,
                    content
                })
            }
        });
    };
    const addNote = async (data) => {
        const res = await fetch('/api/notes/addNotes', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        if(res.ok){
            setContent('')
            form.resetFields()
            messageApi.open({
                type: 'success',
                content: '添加笔记成功',
            });
        }
    }
    return (
        <div style={{ display: 'flex',flexDirection: 'column',height: '100%' }}>
            {contextHolder}
            <Form form={form} initialValues={{
                title: location.state?.title || '',
            }}>
                <Form.Item
                    label="标题"
                    name="title"
                    rules={[{ required: true, message: '请输入标题!' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
            <div style={{ flex: 1 }}>
                <MdEditor value={content} style={{ height: '100%' }} renderHTML={text => mdParser.render(text)} onChange={({ html, text }) => setContent(text)} />
            </div>
            <Button style={{margin: '10px 0'}} type="default">取消</Button>
            <Button type="primary" onClick={onSubmit}>提交</Button>
        </div>
    );
};
export default MarkdownEditor;